<?php
namespace app\admin\controller;

use app\admin\exception\AdminException;
use think\Request;
use think\Db;


class Finance extends Admin
{

    public function initialize() {
        parent::initialize();
        $this->service = model('custom/CustomFee', 'service');
    }

    public function batch(Request $request) {
        $maps = [];
        if ($request->param('type') && $request->param('type') != -1) {
            $maps[] = ['type','=',$request->param('type')];
        }
        if ($request->param('keyword')) {
            $current_ids = model('custom/Custom')->where('nickname|mobile','like',$request->param('keyword').'%')->column('current_id');
            $current_ids = array_unique($current_ids);
            if ($current_ids) {
                $maps[] = ['current_id','in',$current_ids];
            }
        }
        $list = $this->service->lists($maps,'create_time DESC',$this->page,$this->limit,true,['custom']);

        return $this->render('batch', [
            'list' => $list,
        ]);
    }

    public function trend() {
        // 饼图
        $baidu_sum = model('site/Site')->where("FIND_IN_SET('baidu',type)")->count();
        $wechat_sum = model('site/Site')->where("FIND_IN_SET('wechat',type)")->count();
        $alipay_sum = model('site/Site')->where("FIND_IN_SET('alipay',type)")->count();
        $sums = [
            'baidu' => $baidu_sum,
            'wechat' => $wechat_sum,
            'alipay' => $alipay_sum,
        ];
        $this->assign('sums',json_encode($sums));

        // 走势图
        $day_num = 15;
        $dates = [];
        for ($i = 1; $i <= $day_num; $i++) {
            $dates[] = date('m-d', strtotime('-'.$i.' days'));
        }
        sort($dates);
        // 充值消费记录
        $sql = "SELECT FROM_UNIXTIME(create_time, '%Y-%m-%d') AS time, count(*) AS num,type";
        $sql .= " FROM custom_fee";
        $sql .= " WHERE DATE_SUB(CURDATE(), INTERVAL ".count($dates)." DAY) <= DATE(FROM_UNIXTIME(create_time, '%Y-%m-%d'))";
        $sql .= " GROUP BY time,type";
        $first = \think\Db::query($sql);
        $fees_arr = [];
        if ($first) {
            foreach ($first as $v) {
                $date_arr = explode('-',$v['time']);
                array_shift($date_arr);
                $date = implode('-', $date_arr);

                if ($v['type'] == 'recharge') {
                    $fees_arr[$date]['recharge'] = $v['num'];
                } else {
                    $fees_arr[$date]['deduction'] = $v['num'];
                }
            }
        }

        $return_first = $return_second = $users = [];
        foreach ($dates as $k => $v) {
            $return_first[$k] = 0;
            $return_second[$k] = 0;
            if (isset($fees_arr[$v])) {
                if (isset($fees_arr[$v]['recharge'])) {
                    $return_first[$k] = $fees_arr[$v]['recharge'];
                }
                if (isset($fees_arr[$v]['deduction'])) {
                    $return_second[$k] = $fees_arr[$v]['deduction'];
                }
            }
        }
        $this->assign('stack',json_encode(['dates' => $dates,'recharge' => $return_first, 'deduction' => $return_second]));
//        print_r($return_first);
//        print_r($return_second);
//        die;


        return $this->render('trend');
    }

    /**
     * @power 客户管理|客户列表@添加客户
     */
    public function save(Request $request)
    {
        $result = $this->validate($request->post(), 'app\custom\validate\Custom.add');

        if (true !== $result) {
            return json()->data(['code' => 1, 'message' => $result]);
        }

        $result = $this->service->create($request->post());

        if (!$result) {
            throw new AdminException($this->service->getError());
        }

        return json(['code' => 0, 'toUrl' => url('/admin/custom'), 'message' => '创建成功']);
    }

    /**
     * @power 客户管理|客户列表@编辑客户
     */
    public function update(Request $request, $current_id)
    {
        $custom = $this->service->detail(['current_id'=>$current_id]);
        if (!$custom) {
            $this->error('客户不存在');
        }

        $result = $this->validate($request->post(), 'app\custom\validate\Custom.edit');

        if (true !== $result) {
            return json()->data(['code' => 1, 'message' => $result]);
        }

        $result = $this->service->save($request->post(),$current_id);

        if (!$result) {
            throw new AdminException($this->service->getError());
        }

        return json(['code' => 0, 'toUrl' => url('/admin/custom'), 'message' => '编辑成功']);

    }

    /**
     * @power 客户管理|客户列表@客户充值
     */
    public function recharge(Request $request, $current_id)
    {
        if ($request->isPost()){
            $result = $this->validate($request->post(), 'app\custom\validate\Custom.recharge');
            if (true !== $result) {
                return json()->data(['code' => 1, 'message' => $result]);
            }
            $result = $this->service->recharge($current_id,$request->post('money'),$request->post('remark'));
            if (!$result) {
                throw new AdminException($this->service->getError());
            }
            return json(['code' => 0, 'toUrl' => url('/admin/custom'), 'message' => '充值成功']);
        }
        $info = $this->service->detail(['current_id'=>$current_id]);
        return $this->render('recharge', [
            'info' => $info,
        ]);

    }

    /**
     * @power 客户管理|客户列表@客户扣费
     */
    public function deduction(Request $request, $current_id)
    {
        if ($request->isPost()){
            $result = $this->validate($request->post(), 'app\custom\validate\Custom.deduction');
            if (true !== $result) {
                return json()->data(['code' => 1, 'message' => $result]);
            }
            $result = $this->service->deduction($current_id,$request->post('money'),$request->post('remark'));
            if (!$result) {
                throw new AdminException($this->service->getError());
            }
            return json(['code' => 0, 'toUrl' => url('/admin/custom'), 'message' => '扣费成功']);
        }
        $info = $this->service->detail(['current_id'=>$current_id]);
        return $this->render('deduction', [
            'info' => $info,
        ]);

    }

    /**
     * @power 客户管理|客户列表@删除客户
     */
    public function delete($current_id)
    {
        $result = $this->service->destroy($current_id);
        if (!$result) {
            throw new AdminException($this->service->getError());
        }

        return json(['code' => 0, 'message' => '删除成功']);
    }

    /**
     * @power 客户管理|客户列表@禁用客户
     */
    public function forbidden($current_id)
    {
        $result = $this->service->save(['status'=>-1],$current_id);
        if (!$result) {
            throw new AdminException($this->service->getError());
        }

        return json(['code' => 0, 'message' => '禁用成功']);
    }

    /**
     * @power 客户管理|客户列表@解禁客户
     * @method POST
     */
    public function unforbidden($current_id)
    {
        $result = $this->service->save(['status'=>1],$current_id);
        if (!$result) {
            throw new AdminException($this->service->getError());
        }

        return json(['code' => 0, 'message' => '解禁成功']);
    }
}